import threading
import time
import pandas as pd
import tablib as tb
import datetime as dt
import common.constants as const
from services.factory_hq import HQFactory
from common.helper_log import LogHelper as log
from common.helper_ding import DingHelper as ding_helper

class HqService():
    hqFactory = None
    def __init__(self, args=(), kwargs={}):
        super(HqService, self).__init__()
        self.hqFactory = HQFactory()

        
    def get_kline_day_all_for_once(self):
        """行情服务，对外接口"""
        try:            
            # exist = False

            # dfprogress = self.tushareHelper.get_progress(code)

            # if dfprogress.shape[0] > 0:
            #     start_date = dfprogress['enddate'].iloc[0]
            #     exist = True
            # else:
            #     start_date = '20200101'
            start_date = '20150101'
            end_date = dt.datetime.now().strftime('%Y%m%d')

            # 如果有数据了，增量获取（通过日期获取） 没有进度视为全量获取；
            # 当前量不大，可以全量获取
                
            for contract in const.CODE_LIST:
                try:
                    log.log_info(f'开始获取【{contract}】[{start_date}-{end_date}]K线数据')
                    df = self.hqFactory.get_kline_day(contract, start_date=start_date, end_date=end_date)
                    
                    if df is not None:
                        df.Name = contract
                        
                        msg = (f'获取【{contract}】K线数据成功,开始保存数据')
                        log.log_info(msg)
                        self.hqFactory.save_kline(df)
                        self.hqFactory.save_progress(contract, start_date, end_date)
                        time.sleep(1)
                    else: 
                        msg = (f'获取【{contract}】K线数据为空') 
                        log.log_info(msg)

                except Exception as e:
                    msg = (f'【HqService_foronce】(save_kline)获取【{contract}】K线数据失败:{e}')
                    log.log_error(msg)

        except Exception as e:
            msg = (f'【HqService】(get_kline_day_all_for_once)获取K线数据失败:{e}')
            log.log_error(msg)


    def get_kline_day_currentday(self):
        """行情服务，对外接口"""
        try:   
            ding = ding_helper()

            str_today = dt.datetime.now().strftime('%Y%m%d')

            # 如果有数据了，增量获取（通过日期获取） 没有进度视为全量获取；
            # 当前量不大，可以全量获取
            tscode = f"{','.join( x for x in const.CODE_LIST)}"

            for _ in range(3):
                df = self.hqFactory.get_kline_day(tscode, start_date=str_today, end_date=str_today)
                
                if df is None or df.shape[0] == 0:
                    msg = (f'获取当前交易日[{str_today}]K线数据为空; 30秒后重试')
                    log.log_info(msg)
                    time.sleep(30)
                else:                
                    msg = (f'success[{str_today}]：')
                    log.log_info(msg)
                    break

            return df
        except Exception as e:
            msg = (f'【HqService】(get_kline_day_currentday)获取K线数据失败:{e}')
            log.log_error(msg)
